<template>
  <div class='container'>
    <div class="card">
      <!-- 学科名称 -->
      <div class="elRow">
      <el-row>
      <el-col :span="18">
        <div class="grid-content bg-purple">
         <el-form class="FromBox">
          <el-form-item label="学科名称" class="elFrom">
            <el-input v-model="subjectName" size="small" ></el-input>
            </el-form-item>
          <el-form-item>
            <el-button size="small" @click="clearClick">清除</el-button>
            <el-button type="primary" size="small" @click="changeValue">搜索</el-button>
          </el-form-item>
         </el-form>
        </div>
        </el-col>
      <el-col :span="6" style="text-align: right;">
        <div class="grid-content bg-purple-light">
        <el-button type="success" size="small" icon="el-icon-edit" class="elButton" @click="addClick">新增学科</el-button>
        </div>
        </el-col>
      </el-row>
    </div>
    <!-- 数据一共4条 -->
    <div class="elAlert">
      <template >
        <el-alert :title="`数据一共${total}条`" type="info" show-icon :closable="false"></el-alert>
      </template>
    </div>
    <!-- 学科表格 -->
    <div>
      <el-table :data="tableData" style="width: 100%" :header-cell-style="{ background: '#fafafa' }" cellspacing="1"  cellpadding="5"  class="el-table__header">
    <el-table-column type="index"  label="序号" width="80"  align="center">
    </el-table-column>
    <el-table-column prop="subjectName" label="学科名称" width="120" align="center"> </el-table-column>
    <el-table-column prop="username" label="创建者"  width="140"  align="center"></el-table-column>
    <el-table-column prop="addDate" label="创建日期" width="190"  align="center">
      <template v-slot="{row}">
        <span>{{ StringDateToDate(row.addDate) }}</span>
      </template>
    </el-table-column>
    <el-table-column prop="isFrontDisplay" label="前台是否显示" width="110"  align="center">
      <template v-slot="{row}">
        <span v-if="row.isFrontDisplay===1">是</span>
        <span v-if="row.isFrontDisplay===0">否</span>
      </template>
       </el-table-column>
    <el-table-column prop="twoLevelDirectory" label="二级目录" width="100"  align="center"> </el-table-column>
    <el-table-column prop="tags" label="标签" width="100"  align="center"> </el-table-column>
    <el-table-column prop="totals" label="题目数量" width="100"  align="center"> </el-table-column>
    <el-table-column  label="操作" width="260"  align="center">
    <template v-slot="{row}" >
     <el-button  type="text" size="small" @click="classifyClick(row)"> 学科分类 </el-button>
     <el-button  type="text" size="small" @click="labelClick(row)"> 学科标签 </el-button>
     <el-button  type="text" size="small" @click="editClick(row.id)"> 修改 </el-button>
     <el-button  type="text" size="small" @click="deleteClick(row.id)"> 删除 </el-button>
    </template>
    </el-table-column>
  </el-table>
    </div>
    <!-- 分页 size-change 每页条数发生改变 current-change当前页改变 current-page当前页数 page-size每页显示条目个数-->
    <el-row>
      <el-col :span="24" style="text-align: right;" class="Pagination">
    <div class="grid-content bg-purple-dark">
      <el-pagination  @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="page" :page-sizes="[5, 10, 20, 50]"  background :total="total"
      :page-size="pagesize" layout="prev, pager, next, sizes, jumper" > </el-pagination>
    </div>
  </el-col>
  </el-row>
  <!-- 模态框 -->
  <el-dialog  :title="edit?'修改学科':'新增学科'" :visible.sync="dialogFormVisible" width="400px">
  <el-form :model="form" :rules="rules" ref="ruleForm" label-width="80px">
    <el-form-item label="学科名称" prop="subjectName" >
      <el-input v-model="form.subjectName" autocomplete="off" placeholder="请输入学科名称" ></el-input>
    </el-form-item>
    <el-form-item label="是否显示" prop="isFrontDisplay">
    <el-switch v-model="form.isFrontDisplay" active-color="#13ce66"></el-switch>
  </el-form-item>
  </el-form>
  <div slot="footer" class="dialog-footer">
    <el-button @click="resetForm">取 消</el-button>
    <el-button type="primary" @click="submitForm">确 定</el-button>
  </div>
</el-dialog>
    </div>
    </div>
</template>

<script>
import { list, remove, add, detail, update } from '@/api/hmmm/subjects'
// import dayjs from 'dayjs'
export default {
  data () {
    return {
      dialogFormVisible: false, // 模态框默认关闭
      edit: false, // 来控制点击的是编辑还是新增 编辑为true 新增为false
      subjectName: '', // 输入框的值
      total: 0, // 总数
      page: 1, // 当前页码
      pages: 2, // 总页数
      pagesize: 10, // 每页显示多少条数据
      tableData: [], // 表单内容
      form: {
        id: '',
        subjectName: '',
        isFrontDisplay: true
      },
      // 非空正则校验
      rules: {
        name: [
          { required: true, message: '请输入学科名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ]
      }

    }
  },
  created () {
    // 调用学科列表请求
    this.subjectsList()
  },
  methods: {
    // 发送axios请求 进行页面渲染
    async subjectsList () {
      try {
        const { data } = await list({
          subjectName: this.subjectName,
          page: this.page,
          pagesize: this.pagesize
        })
        this.tableData = data.items
        this.total = data.counts
      } catch (error) {
        console.log(error)
      }
    },
    // 字符串时间转正常格式
    StringDateToDate (str) {
      // 输入的字符串
      var input = str
      // 将输入字符串解析为日期对象
      var date = new Date(input)
      // 使用Date对象的方法将其格式化为所需的字符串格式
      var output = date.toISOString().replace('T', ' ').replace(/\.\d{3}Z$/, '')
      // console.log(output) // 输出：2023-04-18 08:53:38
      return output
    },
    // 每页条数发生改变
    handleSizeChange (newSize) {
      console.log(newSize)
      // 将监听的每页显示多少条数据赋值给当前
      this.pagesize = newSize
      // 重新发请求
      this.subjectsList()
    },
    //  当前页改变
    handleCurrentChange (newPage) {
      console.log(newPage)
      // 将监听接受到的页码值的数据 newPage 赋值给 pagenum
      this.page = newPage
      // 重新发请求
      this.subjectsList()
    },
    // 点击搜索框
    changeValue () {
      this.page = 1
      this.pagesize = 5
      this.subjectsList()
    },
    // 点击清除按钮
    clearClick () {
      this.form.subjectName = ''
    },
    // 学科分类
    classifyClick ({ id, subjectName }) {
      console.log(id, subjectName)
      this.$router.push({ path: '/subjects/directorys', query: { id, name: subjectName } })
    },
    // 学科标签
    labelClick ({ id, subjectName }) {
      this.$router.push({ path: '/subjects/tags', query: { id, name: subjectName } })
    },
    // 新增学科
    addClick () {
      this.dialogFormVisible = true
      this.edit = false
    },
    // 编辑学科
    async editClick (id) {
      this.dialogFormVisible = true
      this.edit = true
      this.form.id = id
      try {
        // 发送编辑学科的请求 进行数据回显功能
        const res = await detail({ id })
        console.log(res)
        this.form = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 删除学科
    deleteClick (id) {
      console.log(id)
      this.$confirm('此操作将永久删除该学科, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        this.$message({
          // 发送删除学科的请求
          type: 'success',
          message: '删除成功!'
        })
        try {
          await remove({ id })
          // 调用学科列表请求
          this.subjectsList()
        } catch (error) {
          console.log(error)
        }
      })
    },
    // 点击模态框确定按钮
    submitForm () {
      this.$refs.ruleForm.validate(async (valid) => {
        if (valid) {
          // 条件判断 若为true 则发送修改的请求 若为fales 则发送新增的请求
          if (this.edit) {
            console.log(this.edit)
            // 发送修改的请求
            const obj = {
              id: this.form.id,
              subjectName: this.form.subjectName,
              isFrontDisplay: this.form.isFrontDisplay ? 1 : 0
            }
            try {
              const res = await update(obj)
              console.log(res)
              this.$message('编辑成功')
            } catch (error) {
              console.log(error)
            }
          } else {
            console.log(this.edit)
            try {
              // 发送新增的请求
              const res = await add({
                subjectName: this.form.subjectName,
                isFrontDisplay: this.form.isFrontDisplay ? 1 : 0
              })
              console.log(res)
              this.$message('新增成功')
            } catch (error) {
              console.log(error)
            }
          }
          // 调用学科列表请求
          this.subjectsList()
          this.dialogFormVisible = false
          this.$refs.ruleForm.resetFields()
        } else {
          this.$message('请输入正确信息')
          return false
        }
      })
    },
    // 点击模态框取消按钮
    resetForm () {
      this.dialogFormVisible = false
      this.$refs.ruleForm.resetFields()
      this.$message('已取消')
    }
  }
}
</script>

<style scoped lang='scss'>
.container {
  // padding: 0 10px;
  margin: 5px 0;
  width: 100%;
  height: 100%;
  background: #ebedf0;
}
.card {
  width: 100%;
  height: 100%;
  padding: 20px 20px;
  background: #fff;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border: 1px solid #ebeef5;
  background-color: #fff;
  color: #303133;
  transition: .3s;
  border-radius: 4px;
  overflow: hidden;
}
.FromBox {
  box-sizing: inherit;
  display: flex;
  color: #303133;
}
.elFrom {
  margin-left: 20px;
  display: flex;
  margin-right: 10px;
}
.elButton {
  text-align: right;
  margin-right: 10px;
}
.elAlert {
  margin-bottom: 20px;
}
.el-table .btn-next .warning-row {
    background: oldlace;
  }
.el-table .success-row {
    background: #f0f9eb;
  }
.el-table__header {
  font-size: 14px;
    color: #606266
}
::v-deep  .el-table__header  .el-table__cell .el-button--small {
  font-size: 14px;
}
.Pagination .grid-content {
  display: flex;
  justify-content: right;
  margin-top: 10px;
}
 ::v-deep .el-pagination  .el-pagination__jump {
  margin-left: 3px;
  z-index: 9999;
}
.dialog-footer {
  display: flex;
  justify-content: right;
}
</style>
